package cool.taomu.toolkit.watcher

import com.google.common.eventbus.EventBus
import com.google.common.eventbus.Subscribe
import com.google.inject.AbstractModule
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.TaomuGuice
import cool.taomu.toolkit.platform.inter.AbsPlatform
import cool.taomu.toolkit.provider.EventBusProvider
import cool.taomu.toolkit.utils.ReflectionsScanner
import java.nio.file.FileSystems
import java.nio.file.WatchService
import org.reflections.scanners.Scanners

class WatcherPlugin extends AbsPlatform {

	override note() {
		"目录监控插件"
	}

	override packages() {
	}

	override module(TaomuConfigure config) {
		new AbstractModule() {
			override configure() {
				TaomuGuice.binder(binder(), EventBus)
				.toProvider(EventBusProvider).asEagerSingleton
				bind(WatchService).toInstance(FileSystems.getDefault().newWatchService())
				bind(DirectoryWatcher).asEagerSingleton
			}
		}
	}

	override start() {
	}

	override init() {
		// 获取所有声明了 @Subscribe 注解的方法的类
		var listenerClasses = ReflectionsScanner.scanType(
			Subscribe,
			"coo.taomu.toolkit.test",
			Scanners.MethodsAnnotated
		);

		for (Class<?> clazz : listenerClasses) {
			try {
				var Object listenerInstance = clazz.getDeclaredConstructor().newInstance();
				var eventBus = this.context.getInstance(EventBus) as EventBus
				eventBus.register(listenerInstance);
				System.out.println("已注册监听器: " + clazz.getName());
			} catch (Exception e) {
				System.err.println("注册监听器失败: " + clazz.getName());
				e.printStackTrace();
			}
		}
		this.context.executor.submit([
			(this.context.getInstance(DirectoryWatcher) as DirectoryWatcher).watch();
		])
	}

}
